package com.automailerbot.mailreader;

import javax.mail.*;
import javax.mail.internet.MimeMultipart;
import java.util.Properties;
import org.springframework.stereotype.Service;

@Service
public class OutlookMailReader {

    public void readInbox(String email, String password) throws Exception {
        Properties props = new Properties();
        props.put("mail.store.protocol", "imaps");

        Session session = Session.getDefaultInstance(props);
        Store store = session.getStore();
        store.connect("outlook.office365.com", email, password);

        Folder inbox = store.getFolder("INBOX");
        inbox.open(Folder.READ_ONLY);

        Message[] messages = inbox.getMessages();
        int count = Math.min(messages.length, 5);

        for (int i = messages.length - count; i < messages.length; i++) {
            Message msg = messages[i];
            System.out.println("📧 Subject: " + msg.getSubject());
            System.out.println("From: " + msg.getFrom()[0]);
            System.out.println("Content: " + getTextFromMessage(msg));
            System.out.println("----------------------");
        }

        inbox.close(false);
        store.close();
    }

    private String getTextFromMessage(Message message) throws Exception {
        if (message.isMimeType("text/plain")) {
            return message.getContent().toString();
        } else if (message.isMimeType("multipart/*")) {
            MimeMultipart multipart = (MimeMultipart) message.getContent();
            return multipart.getBodyPart(0).getContent().toString();
        }
        return "";
    }
}
